import 'dart:typed_data';

import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/ext.dart';
import 'package:safetymonitor/app/core/utils/file_util.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/api/file_upload_apis.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';

/// 自定义图片选择器
/// [title] 标题
/// [callback] 回调
/// [imagesList] 已选择的图片列表
/// [isRequired] 是否必填
/// [maxCount] 最大选择数量
/// [titleTextStyle] 标题文字样式
///[isEnabled] 是否可编辑
///[isShowTitle] 是否显示标题
class CustomPickerPhoto extends StatefulWidget {
  const CustomPickerPhoto({
    required this.title,
    required this.imagesList,
    this.callback,
    super.key,
    this.isRequired = false,
    this.maxCount,
    this.titleTextStyle,
    this.isEnabled = true,
    this.isShowTitle = true,
    this.onImage,
  });

  final String title; //标题
  final Function(List<String> path)? callback; //回调
  final void Function(Uint8List data)? onImage;
  final List<String> imagesList; // 已选择的图片列表
  final bool isRequired; //是否必填
  final int? maxCount; //最大选择数量
  final TextStyle? titleTextStyle; // 标题文字样式
  final bool isEnabled; //是否可编辑
  final bool isShowTitle; //是否可编辑

  @override
  State<CustomPickerPhoto> createState() => _CustomPickerPhotoState();
}

class _CustomPickerPhotoState extends State<CustomPickerPhoto> {
  // //当前显示的内容
  // List<String> imageList = [];

  @override
  void initState() {
    super.initState();
    _initView();
  }

  _initView() {
    // if (widget.imagesList != null && widget.imagesList!.isNotEmpty) {
    //   imageList.addAll(widget.imagesList!);
    // }
  }

  /// 拍摄或者从相册中选择图片
  void selectPhoto(ImageSource source) async {
    final ImagePicker picker = ImagePicker();

    /// 从相册中选取
    final XFile? image = await picker.pickImage(source: source, imageQuality: 30);
    if (image != null) {
      widget.onImage?.call(await image.readAsBytes());
      final images = await FileUploadApis.uploadFile(fileUrl: image.path);
      if (images != '') {
      } else {
        AppToast.showWarning('上传失败');
      }
      widget.imagesList.add(images);
      //进行回调
      if (widget.callback != null) {
        widget.callback!(widget.imagesList);
      }
      setState(() {});
    } else {
      AppToast.showWarning('未选择图片');
    }
  }

  /// 判断是否还能添加图片
  Widget addImg(List<String> images) {
    if (!widget.isEnabled) {
      return Container();
    }
    if (images.length < (widget.maxCount ?? 9)) {
      return Container(
        width: 80.w,
        height: 80.w,
        margin: EdgeInsets.only(bottom: 10.w),
        decoration: BoxDecoration(
          color: const Color(0xffF7F7FB),
          border: Border.all(
            color: const Color(0xffEBEDF0),
          ),
          borderRadius: BorderRadius.circular(8.w),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.photo_camera_outlined,
              color: const Color(0xff8D95A3),
              size: 25.w,
            ),
            AppGaps.vGap6,
            Text(
              '点击上传',
              style: TextStyle(
                color: const Color(0xff8D95A3),
                fontSize: 12.sp,
              ),
            ),
          ],
        ),
      ).clickOnce(() {
        showCupertinoModalPopup(
          context: context,
          builder: (context) {
            return CupertinoActionSheet(
              actions: [
                CupertinoActionSheetAction(
                  child: const Text('拍照'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    selectPhoto(ImageSource.camera);
                  },
                ),
                CupertinoActionSheetAction(
                  child: const Text('从相册选择'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    selectPhoto(ImageSource.gallery);
                  },
                ),
              ],
              cancelButton: CupertinoActionSheetAction(
                onPressed: Navigator.of(context).pop,
                child: const Text('取消'),
              ),
            );
          },
        );
      });
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Visibility(
          visible: widget.isShowTitle,
          child: Column(
            children: [
              AppGaps.vGap10,
              Row(
                children: [
                  Visibility(visible: widget.isRequired, child: Text('*', style: TextStyle(color: Colors.red, fontSize: 14.sp))),
                  AppGaps.hGap2,
                  Text(
                    widget.title,
                    style: widget.titleTextStyle ??
                        TextStyle(
                          color: Colors.black,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.bold,
                        ),
                  ),
                  const Spacer(),
                  Visibility(
                      visible: widget.isEnabled,
                      child: Text(
                        '${widget.imagesList.length}/${widget.maxCount ?? 9}',
                        style: TextStyle(color: const Color(0xff8D95A3), fontSize: 12.sp),
                      )),
                ],
              ),
              AppGaps.vGap12,
            ],
          ),
        ),
        Wrap(
          spacing: 5.w,
          children: widget.imagesList.map<Widget>((item) {
            return Stack(
              children: [
                Container(
                  width: 80.w,
                  height: 80.w,
                  margin: EdgeInsets.only(bottom: 10.w),
                  decoration: BoxDecoration(
                    color: const Color(0xffF7F7FB),
                    border: Border.all(
                      color: const Color(0xffEBEDF0),
                    ),
                    borderRadius: BorderRadius.circular(8.w),
                    image: DecorationImage(
                      image: NetworkImage(item.contains('http') ? item : Interface.fileUrl + item),
                      fit: BoxFit.cover,
                    ),
                  ),
                ).clickOnce(() {
                  //打开文件
                  FileUtils.openFile(item.contains('http') ? item : Interface.fileUrl + item);
                }),
                Visibility(
                    visible: widget.isEnabled,
                    child: Positioned(
                      right: 5.w,
                      top: 5.w,
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            widget.imagesList.remove(item);
                            //进行回调
                            if (widget.callback != null) {
                              widget.callback!(widget.imagesList);
                            }
                          });
                        },
                        child: Container(
                          width: 20.w,
                          height: 20.w,
                          decoration: BoxDecoration(
                            color: const Color(0xffF7F7FB),
                            borderRadius: BorderRadius.circular(10.w),
                          ),
                          child: Icon(
                            Icons.close,
                            color: const Color(0xff8D95A3),
                            size: 15.w,
                          ),
                        ),
                      ),
                    )),
              ],
            );
          }).toList()
            ..add(addImg(widget.imagesList)),
        ),
        AppGaps.vGap5,
      ],
    );
  }
}
